//
//  PGTopicManager.m
//  PhotographicGuide
//
//  Created by indream on 13-4-12.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGTopicManager.h"
#import "PGCoreDataManager.h"
#import "PGArticle.h"
#import "SBJson.h"
static PGTopicManager *_instance;
static NSString* NOTIFICATION_TOPIC_DATA_LOADED = @"__NOTIFICATION_TOPIC_DATA_LOADED__";
static NSString* NOTIFICATION_TOPIC_LIST_LOADED = @"__NOTIFICATION_TOPIC_LIST_LOADED__";
static NSString* NOTIFICATION_TOPIC_TABLE_REFRESH = @"__NOTIFICATION_TOPIC_TABLE_REFRESH__";
static NSString*topicURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_topic.php";
static NSString*topicMenuURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_topic.php?mod=list";
@implementation PGTopicManager

-(id)init{
    self = [super init];
    if(self){
        self.queue = [[NSOperationQueue alloc]init];
        SBJsonParser *topicListJson = [[SBJsonParser alloc]init];
        NSString *topicJsonPath = [[NSBundle mainBundle]pathForResource:@"topic" ofType:@"json"];
        _topicList = [[topicListJson objectWithString:[NSString stringWithContentsOfFile:topicJsonPath encoding:NSUTF8StringEncoding error:nil]]objectForKey:@"list"];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dataLoaded:) name:NOTIFICATION_TOPIC_DATA_LOADED object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(listLoaded:) name:NOTIFICATION_TOPIC_LIST_LOADED object:nil];
    }
    return self;
}
#pragma mark - public
-(void)addQperator:(PGHttpOperator*)operator{
    [_queue addOperation:operator];
}
-(void)requestWithTag:(NSString*)tag{
    NSTimeInterval timeInterval = floor([[NSDate date]timeIntervalSince1970]/86400)*86400;
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[topicURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?isdebug=0&count=%d&time=%d&tag=%@",10,(int)timeInterval,[tag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] cache:YES notification:NOTIFICATION_TOPIC_DATA_LOADED]];
}
-(void)requestList{
    NSTimeInterval timeInterval = floor([[NSDate date]timeIntervalSince1970]/86400)*86400;
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[topicMenuURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"&time=%d",(int)timeInterval]] cache:YES notification:NOTIFICATION_TOPIC_LIST_LOADED]];
}
#pragma mark - private

-(void)listLoaded:(NSNotification*)notification{
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    self.topicList = [json objectForKey:@"list"];
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_TOPIC_TABLE_REFRESH object:nil userInfo:nil];
}
-(void)dataLoaded:(NSNotification*)notification{
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    if([[json objectForKey:@"code"]intValue]==0){
        self.list = [json objectForKey:@"list"];
        int count = _list.count;
        for (int i=0; i<count; i++) {
            [self addArticle:[_list objectAtIndex:i]];
        }
        [[PGCoreDataManager sharedInstance]save];
    }
    NSLog(@"data loaded!!");
    [self performSelectorOnMainThread:@selector(postFinishLoad) withObject:nil waitUntilDone:YES];
}
-(void)postFinishLoad{
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_TOPIC_TABLE_REFRESH object:nil userInfo:nil];
}
-(void)addArticle:(NSDictionary*)dict{
    NSNumber *articleId = [NSNumber numberWithInt:[[dict objectForKey:@"id"]intValue]];
    NSNumber *media = [NSNumber numberWithInt:[[dict objectForKey:@"media"]intValue]];
    NSNumber *time = [NSNumber numberWithInt:[[dict objectForKey:@"time"]intValue]];
    NSNumber *ispub = [NSNumber numberWithInt:[[dict objectForKey:@"ispub"]intValue]];
    NSNumber *views = [NSNumber numberWithInt:[[dict objectForKey:@"views"]intValue]];
    NSNumber *favors = [NSNumber numberWithInt:[[dict objectForKey:@"favors"]intValue]];
    NSString *name = [dict objectForKey:@"name"];
    NSString *desc = [dict objectForKey:@"description"];
    NSString *url = [dict objectForKey:@"url"];
    NSString *icon = [dict objectForKey:@"icon"];
    SBJsonWriter *writer = [[SBJsonWriter alloc]init];
    NSString *devices = [writer stringWithObject:[dict objectForKey:@"devices"]];
    NSString *imageSmall = [dict objectForKey:@"imageSmall"];
    NSString *imageMiddle = [dict objectForKey:@"imageMiddle"];
    NSString *imageLarge = [dict objectForKey:@"imageLarge"];
    NSString *author = [dict objectForKey:@"author"];
    NSString *authorUrl = [dict objectForKey:@"authorUrl"];
    NSString *teachUrl = [dict objectForKey:@"teachUrl"];
    
    NSArray *array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId.intValue] entityName:@"Article" fetchLimit:1];
    if(array.count==0){
        PGArticle *article = (PGArticle*)[[PGCoreDataManager sharedInstance]createAndAddDataByEntityName:@"Article"];
        article.articleid = articleId;
        article.media = media;
        article.time = time;
        article.devices = devices;
        article.ispub = ispub;
        article.views = views;
        article.favors = favors;
        article.name = name;
        article.desc = desc;
        article.url = url;
        article.icon = icon;
        article.imageSmall = imageSmall;
        article.imageMiddle = imageMiddle;
        article.imageLarge = imageLarge;
        article.author = author;
        article.authorUrl = authorUrl;
        article.teachUrl = teachUrl;
    }
}
+(PGTopicManager*)sharedManager{
    if(_instance==nil){
        _instance = [[PGTopicManager alloc]init];
    }
    return _instance;
}
@end
